const util = require("../../utils/utils");
const toast = require("../../utils/toasts");
const session = require("../../utils/session");

import {
  card_getCode,
  card_bindPhone
} from "../../utils/api.js";

Component({
  properties: {
    show: {
      type: Boolean, //必填，目前接受的类型包括：String, Number, Boolean, Object, Array, null（表示任意类型）
      value: false //可选，默认值，如果页面没传值过来就会使用默认值
    }
  },
  methods: {
    dataInit() {
      let active = this.properties.active;
      this.setData({
        filterActive: active
      })
    },
    handlePhoneChange: function(e) {
      let phone = e.detail.value;
      this.setData({
        phone
      });
    },
    handleCodeChange: function (e) {
      let code = e.detail.value;
      this.setData({
        code
      });
    },
    handleSendCode: function() {
      let phone = this.data.phone;
      if (!phone) {
        return toast.show("请输入手机号");
      };
      if (!util.phone_validate(phone)) {
        return toast.show("请输入合法手机号");
      };

      card_getCode({
        phone: phone
      }).then(res => {
        // console.log(res);
        if (res.success) {
          let time = 10;
          this.setData({
            time
          });
          let timer = setInterval(() => {
            time -= 1;
            this.setData({
              time
            });
            if (time <= 0) {
              clearInterval(timer);
            };
          }, 1000);
        } else {
          toast.show(res.errorMsg);
        }

      });

    },
    bindPhone: function() {
      let phone = this.data.phone;
      let code = this.data.code;
      if (!phone) {
        return toast.show("请输入手机号");
      };
      if (!util.phone_validate(phone)) {
        return toast.show("请输入合法手机号");
      };
      if (!code) {
        return toast.show("请输入验证码");
      };
      var that = this;
      card_bindPhone({
        phone: phone,
        code: code
      }).then(res => {
        if (res.success) {
          var userInfo = session.getUserSync();
          if (userInfo) {
            userInfo.phone = phone;
            session.putUser(userInfo);

            that.setData({
              user: userInfo
            });
          }

          that.hide();
          this.triggerEvent('success', {phone:phone});
        } else {
          toast.show(res.errorMsg);
        }

      });

    },
    hide() {
      this.triggerEvent('close', {});
    }
  }
});